package com.mu.securitysso.authentication;

import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 * @author sht
 */
@Component
public class MyAuthenticationProvider implements AuthenticationProvider {

    private final static Logger logger = LoggerFactory.getLogger(MyAuthenticationProvider.class);


    @Autowired
    private MyUserDetailsService myUserDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Gson gson = new Gson();

        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        logger.info("MyAuthenticationProvider authentication login user  username={},password={}",username,password);

        MyUserDetails myUserDetails = (MyUserDetails)  myUserDetailsService.loadUserByUsername(username);

        logger.info("MyAuthenticationProvider authentication myUserDetails={} ",gson.toJson(myUserDetails));

      if( myUserDetails == null ){
          return (Authentication) new BadCredentialsException("用户没有找到");
      }

      if( !myUserDetails.getPassword().equals(password) ){
          logger.info("MyAuthenticationProvider authentication inputPassword={},dbPassword={}",password,myUserDetails.getPassword());
          return (Authentication) new BadCredentialsException("密码错误");
      }

        return new UsernamePasswordAuthenticationToken(myUserDetails,password,myUserDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
